package com.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.gulimall.product.entity.BrandEntity;
import com.gulimall.product.entity.CategoryEntity;
import org.springframework.stereotype.Service;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.utils.PageUtils;
import com.common.utils.Query;

import com.gulimall.product.dao.CategoryBrandRelationDao;
import com.gulimall.product.entity.CategoryBrandRelationEntity;
import com.gulimall.product.service.CategoryBrandRelationService;

import javax.annotation.Resource;


@Service("categoryBrandRelationService")
public class CategoryBrandRelationServiceImpl extends ServiceImpl<CategoryBrandRelationDao, CategoryBrandRelationEntity> implements CategoryBrandRelationService {

    @Resource
    private CategoryServiceImpl categoryServiceImpl;

    @Resource
    private BrandServiceImpl brandServiceImpl;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryBrandRelationEntity> page = this.page(
                new Query<CategoryBrandRelationEntity>().getPage(params),
                new QueryWrapper<>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveDetail(CategoryBrandRelationEntity categoryBrandRelation) {
        CategoryEntity categoryEntity = categoryServiceImpl.getOne(new QueryWrapper<CategoryEntity>().eq("cat_id", categoryBrandRelation.getCatelogId()));
        categoryBrandRelation.setCatelogName(categoryEntity.getName());
        BrandEntity brandEntity = brandServiceImpl.getById(categoryBrandRelation.getBrandId());
        categoryBrandRelation.setBrandName(brandEntity.getName());
        this.save(categoryBrandRelation);
    }

    /**
     * 更新分类和品牌名，在品牌名和分类名被修改时，就调用这个方法对关系表中的name进行改变
     * @param categoryBrandRelationEntity
     */
    @Override
    public void updateName(CategoryBrandRelationEntity categoryBrandRelationEntity) {
        UpdateWrapper<CategoryBrandRelationEntity> updateWrapper = new UpdateWrapper<>();
        if(categoryBrandRelationEntity.getCatelogId() != null){
            this.update(categoryBrandRelationEntity,updateWrapper.eq("catelog_id",categoryBrandRelationEntity.getCatelogId()));
        }
        if(categoryBrandRelationEntity.getBrandId() != null){
            this.update(categoryBrandRelationEntity,updateWrapper.eq("brand_id",categoryBrandRelationEntity.getBrandId()));
        }
    }

}